package com.saikei.demoapp.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.saikei.demoapp.MainVm
import java.lang.reflect.ParameterizedType

open class BaseVMActivity<VB : ViewDataBinding, VM : BaseInitVM> : AppCompatActivity() {

    protected lateinit var mBinding: VB
    protected lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = createViewBing()
        mViewModel = createViewModel()
        setContentView(mBinding.root)
    }

    private fun createViewBing(): VB {
        val type = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0]
        val clazz = type as Class<VB>
        val inflateMethod = clazz.getMethod("inflate", LayoutInflater::class.java)
        return inflateMethod.invoke(null, layoutInflater) as VB
    }

    protected open fun createViewModel(): VM {
        val type = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[1]
        val clazz = type as Class<VM>
        val factory = BaseInitVM.factory<VM>(app = application, clazz = clazz)
        return ViewModelProvider(this, factory)[clazz]
    }



}